<?php

namespace App\Services\Register;

use App\Models\Account\UserAccountModel;
use App\Models\Account\UserAccountSkuModel;
use App\Models\Assess\ActivateUserManagementEmailModel;
use App\Models\Assess\ActivateUserManagementTagModel;
use App\Models\Assess\AutoEmailModel;
use App\Models\Assess\AutoEmailSkuModel;
use App\Models\Assess\BuyerModel;
use App\Models\Assess\EmailTemplateModel;
use App\Models\Assess\EvaluationMonitoringModel;
use App\Models\Assess\GiftPlatformSkuModel;
use App\Models\Assess\GiftModel;
use App\Models\Assess\OperateModel;
use App\Models\Assess\OperateSkuModel;
use App\Models\Assess\OrderAndCustomersOrderDetailModel;
use App\Models\Assess\OrderAndCustomersOrderExtendModel;
use App\Models\Assess\OrderAndCustomersOrderModel;
use App\Models\Assess\TagManageModel;
use App\Models\Register\ActivateUserManagementInfoModel;
use App\Models\Register\ActivateUserManagementModel;
use App\Services\Assess\ActivateService;
use App\Services\Assess\SendLogService;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\Ding;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Config\Definition\Exception\Exception;

class RegisterService extends BaseService
{
    //当前进度是否激活(0:待激活,1:已激活,2:激活异常,3:激活失败)
    const PROGRESS_ACTIVATE_NEW = 0;
    const PROGRESS_ACTIVATE_ALREADY = 1;
    const PROGRESS_ACTIVATE_ABNORMAL = 2;
    const PROGRESS_ACTIVATE_FAIL = 3;


    public $language = [
        ['label' => 'English', 'val' => 'en'],//英语
        ['label' => 'German', 'val' => 'ger'],//德语
        ['label' => 'Italian', 'val' => 'it'],//意大利语
        ['label' => 'Spanish', 'val' => 'sp'],//西班牙语
        ['label' => 'Japanese', 'val' => 'jp']//日语
    ];


    /**
     * 构造函数
     * @author 牧羊人
     * @since 2020/11/10
     * LoginService constructor.
     */
    public function __construct()
    {
        $this->model = new ActivateUserManagementModel();
    }

    /**
     * @return mixed
     */
    public function register()
    {
        $param = request()->all();
        $list = [];
        $list['name'] = trim($param['name'] ?? '');
        $list['email'] = trim($param['email'] ?? '');
        $list['order_id'] = trim($param['order_id'] ?? '');
        $languageSelect = $param['language_select'] ?? 'en';
        $list['record_id'] = $param['record_id'] ?? 0;
        $progressActivate = self::PROGRESS_ACTIVATE_ALREADY;
        $list['activate_time'] = date('Y-m-d H:i:s');
        $list['create_time'] = time();
        if (empty($list['name'])) {
            return message("Name is invaild!", false, []);
        }
//        if (empty($list['email'])) {
//            return message("请输入正确的Email", false, []);
//        }
        if (empty($list['order_id'])) {
            return message("Order is invaild!", false, []);
        }
        if (!empty($list['email'])){
            $CommonService = new CommonService();
            $emailResponse = $CommonService->emailPreg($list['email']);
//            $emailFormat = $CommonService->emailFormat($list['email']);
//            Log::channel('registerLog')->debug('用户注册邮箱格式信息:',['params' => $list]);
            //验证邮箱格式
//            if (!$emailResponse || !$emailFormat) {
            if (!$emailResponse) {
                return message("Email is invaild!", false, []);
            }
        }

        $emailExp = explode('@',$list['email']);
        $prefix = $emailExp[0] ?? '';
        $endEmail = $emailExp[1] ?? '';
        $endEmailExp = explode('.',$endEmail);
        if (!empty($endEmailExp) && count($endEmailExp)>2){
            $aa = $endEmailExp[0];
            $bb = $endEmailExp[1];
            $cc = $endEmailExp[2];
            $changeEmail = $prefix . '@' . strtolower($aa) . '.' . $bb . '.' . $cc;
            if (strtolower($list['email']) == strtolower($changeEmail)){
                $list['email'] = $changeEmail;
            }
        }else{
            $aa = $endEmailExp[0] ?? '';
            $bb = $endEmailExp[1] ?? '';
            $changeEmail = $prefix . '@' . strtolower($aa) . '.' . $bb;
            if (strtolower($list['email']) == strtolower($changeEmail)){
                $list['email'] = $changeEmail;
            }
        }


        //判断订单是否存在
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $order = $OrderAndCustomersOrderModel->where(['order_id' => $list['order_id'], 'mark' => 1])->first(['id', 'order_id','country_code','create_user','buyer_name']);
        $orderExists = 1;
        if (empty($order)) $orderExists=0;
        if (empty($order) || empty($list['email'])) {
//            return message("订单不存在,请确认", false, []);
            $progressActivate = self::PROGRESS_ACTIVATE_FAIL;
        }


        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $OrderAndCustomersOrderExtendModel = new OrderAndCustomersOrderExtendModel();
        $BuyerModel = new BuyerModel();
        $GiftModel = new GiftModel();
        $GiftPlatformSkuModel = new GiftPlatformSkuModel();

        //获取买家端设置
        $buyerInfo = $BuyerModel->first(['platform_sku_take_precedence','display_comment_link','comment_platform_sku','display_gift_select','comment_gift_platform_sku','auto_comment_monitor']);
        //获取订单信息
        if (!empty($order)){
            $orderExtend = $OrderAndCustomersOrderExtendModel->where(['order_id'=>$order['id']])->first();
            $orderDetail = $OrderAndCustomersOrderDetailModel->where(['order_id' => $order['id']])->get()->toArray();
        }


        $platformSkus = [];
        if (!empty($buyerInfo['platform_sku_take_precedence'])) {
            $platformSkus = explode(';', 'platform_sku_take_precedence');
        }

        $productName = $asin = $platform_sku = $brand = $categoryName = '';
        if (empty($platformSkus)) {
            $productName = $orderDetail[0]['product_title'] ?? '';
            $asin = $orderDetail[0]['asin'] ?? '';
            $platform_sku = $orderDetail[0]['platform_sku'] ?? '';
            $brand = $orderDetail[0]['brand_code'] ?? '';
            $categoryName = $orderDetail[0]['product_category_name1'] ?? '';
        } else {
            foreach ($orderDetail as $val) {
                if (in_array($val['asin'], $platformSkus)) {
                    $productName = $val['product_title'];
                    $asin = $val['asin'];
                    $platform_sku = $val['platform_sku'];
                    $brand = $val['brand_code'];
                    $categoryName = $val['product_category_name1'];
                    break;
                }
            }
        }

//        if (empty($asin)) return message("当前订单没有合适asin,请确认", false, []);

//        $UserAccountModel = new UserAccountModel();
//        $UserAccountSkuModel = new UserAccountSkuModel();
//        $userAccountTable = $UserAccountModel->getTable();
//        $userAccountSkuTable = $UserAccountSkuModel->getTable();
//        $accountSkuData = $UserAccountModel::from("$userAccountTable as m")
//            ->select('m.*')
//            ->join("$userAccountSkuTable as s", 's.user_account_id', '=', 'm.id')
//            ->where(['m.status'=>1])
//            ->where(['m.mark'=>1])
//            ->where(['s.sku'=>$platform_sku])
//            ->first();

        $userGroupId = 0;
//        if (!empty($accountSkuData['user_group_id'])){
//            $userGroupId = $accountSkuData['user_group_id'];
//        }


        //获取礼品信息
        $giftInfo = [];
        if (!empty($order)){

            //判断是否加入评论监控
            if (!empty($buyerInfo['auto_comment_monitor']) && $buyerInfo['auto_comment_monitor']==1){
                $EvaluationMonitoringModel = new EvaluationMonitoringModel();
                $monitorData = [
                    'country'=>$order['country_code'],
                    'asin'=>$asin,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                $monitorExists = $EvaluationMonitoringModel->getOne([
                    ['asin','=',$asin]
                ],'*',false,false);
                if (empty($monitorExists)){
                    $EvaluationMonitoringModel->insert($monitorData);
                    $Ding = new Ding();
                    //发送钉钉
                    $Ding->asinNotice($asin);
                }
            }

            $mainTable = $GiftModel->getTable();
            $sonTable = $GiftPlatformSkuModel->getTable();
            $giftInfo = $GiftModel::from("$mainTable as m")
                ->select('m.*')
                ->join("$sonTable as s", 's.gift_id', '=', 'm.id')
                ->distinct(true)
//                ->where(['m.create_user'=>$userGroupId])
                ->where(['m.status'=>1])
                ->where(['m.mark'=>1])
                ->where(['s.platform_sku'=>$platform_sku])
                ->limit(3)
                ->get()
                ->toArray();
        }

        foreach ($giftInfo as $key=>$val){
            $giftInfo[$key]['image'] = env('IMG_URL').$val['image'];
        }

        //是否需要走留评页面
        $displayCommentLink = 1;
        if (!empty($buyerInfo['display_comment_link']) && $buyerInfo['display_comment_link']==2){
            $commentplatformSku = explode(';',$buyerInfo['comment_platform_sku']);
            if (in_array($platform_sku,$commentplatformSku)) $displayCommentLink=2;
        }

        //是否展示礼品选择界面
        $displayGiftSelect =1;
        if (!empty($buyerInfo['display_gift_select']) && $buyerInfo['display_gift_select']==2){
            $commentGiftPlatformSku = explode(';',$buyerInfo['comment_gift_platform_sku']);
            if (in_array($platform_sku,$commentGiftPlatformSku)) $displayGiftSelect=2;
        }


        $orderAddress = '';
        if (!empty($orderExtend['line1'])) $orderAddress = $orderExtend['line1'] . ' ' . $orderExtend['line2'] . ' ' . $orderExtend['line3'];
        $response = [
            'asin' => $asin,
            'product_title' => $productName,
            'platform_sku' => $platform_sku,
            'brand_code' => $brand,
            'product_category_name1' => $categoryName,
            'gift_info'=>$giftInfo,
            'display_comment_link_view'=>$displayCommentLink,
            'display_gift_select_view'=>$displayGiftSelect,
            'star_rating_evaluation_view'=>0,
            'jump_amazon_comment_view'=>0,
            'jump_amazon_star_view'=>0,
            'order_phone'=>$orderExtend['phone'] ?? '',
            'order_address'=>$orderAddress,
            'order_name'=>$order['buyer_name'] ?? '',
            'order_state'=>$orderExtend['state'] ?? '',
            'order_postal_code'=>$orderExtend['postal_code'] ?? '',
            'order_country_code'=>$order['country_code'] ?? '',
            'order_city_name'=>$orderExtend['city_name'] ?? '',
            'progress_activate'=>$progressActivate,
            'evaluation_process'=>0
        ];

        //获取运营端配置信息
        $OperateModel = new OperateModel();
        $OperateSkuModel = new OperateSkuModel();
        $mainTable = $OperateModel->getTable();
        $sonTable = $OperateSkuModel->getTable();
        if (empty($brand)) $brand = 'NoBrand';
        $operateData = $OperateModel::from("$mainTable as m")
            ->join("$sonTable as s", 's.operate_id', '=', 'm.id')
//            ->where('m.create_user','=',$userGroupId)
            ->where('m.brand','=',$brand)
            ->where('s.sku','=',$platform_sku)
            ->where('m.mark','=',1)
            ->first(['m.id','m.create_user','m.evaluation_process','m.select_mode','m.gift_section','m.register_process',
                'm.star_rating_evaluation','m.jump_amazon_comment','m.jump_amazon_star','m.process_end_page_script_operate','m.bad_reviews_script']);

        $response['operate_list'] = [];
        if (!empty($operateData)){
            $userGroupId = $operateData['create_user'];
            //获取运营配置信息
            $BuyerModel = new BuyerModel();
            $BuyerData = $BuyerModel->getOne([
                ['type','=',1],
                ['brand_code','=',$brand],
                ['create_user','=',$operateData['create_user']],
            ],'gift_select_page_script,comment_page_script,amazon_comment_page_script,gift_product_page_script,gift_end_page_script');

            $response['evaluation_process'] =$operateData['gift_section'];
            $response['display_gift_select_view'] = $operateData['gift_section'];
            $response['star_rating_evaluation_view'] = $operateData['star_rating_evaluation'];
            $response['jump_amazon_comment_view'] = $operateData['jump_amazon_comment'];
            $response['jump_amazon_star_view'] = $operateData['jump_amazon_star'];
            $operateData['process_end_page_script_operate'] = json_decode($operateData['process_end_page_script_operate'],true);
            $badReviewsScript = json_decode($operateData['bad_reviews_script'],true);
            $operateData['bad_reviews_script'] = $this->getBadReviewsLanguage($badReviewsScript,$languageSelect);
            if (!empty($BuyerData)){
                $giftSelectPageScript =json_decode($BuyerData['gift_select_page_script'],true);
                $operateData['gift_select_page_script'] = $this->getGiftSelectLanguage($giftSelectPageScript,$languageSelect);
                $commentPageScript = json_decode($BuyerData['comment_page_script'],true);
                $operateData['comment_page_script'] = $this->getCommentLanguage($commentPageScript,$languageSelect);
                $amazonCommentPageScript = json_decode($BuyerData['amazon_comment_page_script'],true);
                $operateData['amazon_comment_page_script'] = $this->getAmazonCommentLanguage($amazonCommentPageScript,$languageSelect);
                $giftProductPageScript = json_decode($BuyerData['gift_product_page_script'],true);
                $operateData['gift_product_page_script'] = $this->getGiftProductLanguage($giftProductPageScript,$languageSelect);
                $giftEndPageScript = json_decode($BuyerData['gift_end_page_script'],true);
                $operateData['gift_end_page_script'] = $this->getGiftEndLanguage($giftEndPageScript,$languageSelect);
            }else{
                $response['evaluation_process'] =2;
            }
            $response['operate_list'] = $operateData;
        }


//        if (empty($response['operate_list'])) $response['progress_activate'] =2; //激活获取运营端配置不存在
        if (empty($response['operate_list'])) $response['evaluation_process'] =2; //运营没有配置sku 不开启评价后续流程



        $list['asin'] = $asin;
        $list['create_user'] = $userGroupId;
//        $list['product_title'] = $productName;
        $list['platform_sku'] = $platform_sku;
        $list['order_country'] = $response['order_country_code'];

        $response['order_exists'] = $orderExists;//判断订单是否存在

        $info = $this->model->where('order_id', '=', $list['order_id'])->where('mark','=',1)->first();
        if (!empty($info)) return message("success", true, $response);
        $list['progress_activate'] = $progressActivate;
//        if (!empty($operateData['register_process']) && $operateData['register_process'] ==1) $list['progress_activate'] = self::PROGRESS_ACTIVATE_ALREADY;
        $id = $this->model->insertGetId($list);
        if (!$id) return message("Please fill in the correct data as required", false, []);

        //发送自动信 是否有实时发送的自动信  暂时去掉 因为客户存在7分钟时间差找订单 填写等 实时发送会影响客户后续流程
//        $AutoEmailModel = new AutoEmailModel();
//        $AutoEmailSkuModel = new AutoEmailSkuModel();
//        $EmailTemplateModel = new EmailTemplateModel();
//        $mainTable = $AutoEmailModel->getTable();
//        $sonTable = $AutoEmailSkuModel->getTable();
//        $emailTemplateTable = $EmailTemplateModel->getTable();
//        $autoEmailData = $AutoEmailModel::from("$mainTable as m")
//            ->select(['m.id','m.interval_time','m.email_name','e.title','e.content'])
//            ->join("$sonTable as s", 's.auto_email_id', '=', 'm.id')
//            ->join("$emailTemplateTable as e", 'm.template_id', '=', 'e.id')
//            ->where('m.create_user','=',$userGroupId)
//            ->where('e.type','=',1)
//            ->where('m.mark','=',1)
//            ->where('s.sku', '=', $platform_sku)->first();
//        if (!empty($autoEmailData) && $autoEmailData['interval_time'] ==0){
//            $sendData = [
//                'activate_user_id'=>$id,
//                'title'=>$autoEmailData['title'],
//                'content'=>$autoEmailData['content'],
//                'date_time'=>date("Y-m-d H:i:s",time()+2*60),
//                'create_user'=>$userGroupId,
//                'create_time'=>time()
//            ];
//            $ActivateUserManagementEmailModel = new ActivateUserManagementEmailModel();
//            $ActivateUserManagementEmailModel->insert($sendData);
//        }

        return message("success", true, $response);
    }

    /**
     * @Notes:获取买家端设置
     * @Interface getBuyerConfig
     * @author: wuyu
     * @Time: 2023/4/26   15:40
     */
    public function getBuyerConfig()
    {

        $param = request()->all();
        $language = $param['language'] ?? 'en';

        $BuyerModel = new BuyerModel();
        $buyerList = $BuyerModel->getOne([
            ['mark','=',1],
            ['type','=',0],
        ]);
        $buyerList['comment_sensitive_word'] = explode(';',$buyerList['comment_sensitive_word']);
        $registerPageScript = json_decode($buyerList['register_page_script'],true);

        //获取多语言
        $buyerList['register_page_script'] = $this->getActivateLanguage($registerPageScript,$language);
        $buyerList['register_success_page_script'] = !empty($buyerList['register_success_page_script']) ? json_decode($buyerList['register_success_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['register_no_page_script'] = !empty($buyerList['register_no_page_script']) ? json_decode($buyerList['register_no_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['gift_select_page_script'] = !empty($buyerList['gift_select_page_script']) ? json_decode($buyerList['gift_select_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['comment_page_script'] = !empty($buyerList['comment_page_script']) ? json_decode($buyerList['comment_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['amazon_comment_page_script'] = !empty($buyerList['amazon_comment_page_script']) ? json_decode($buyerList['amazon_comment_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['gift_product_page_script'] = !empty($buyerList['gift_product_page_script']) ? json_decode($buyerList['gift_product_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['gift_card_page_script'] = !empty($buyerList['gift_card_page_script']) ? json_decode($buyerList['gift_card_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['gift_cashback_page_script'] = !empty($buyerList['gift_cashback_page_script']) ? json_decode($buyerList['gift_cashback_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['gift_end_page_script'] = !empty($buyerList['gift_end_page_script']) ? json_decode($buyerList['gift_end_page_script'], true) : json_decode('{"script_1": ""}', true);
        $buyerList['language_list'] = $this->language;

        return message("获取成功", true, $buyerList);

    }

    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getActivateLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['register_page_script_ger']) ?
                    json_decode($registerPageScript['register_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['register_page_script_it']) ?
                    json_decode($registerPageScript['register_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['register_page_script_sp']) ?
                    json_decode($registerPageScript['register_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['register_page_script_jp']) ?
                    json_decode($registerPageScript['register_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['register_page_script']) ?
                    json_decode($registerPageScript['register_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }

    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getBadReviewsLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['bad_reviews_script_ger']) ?
                    json_decode($registerPageScript['bad_reviews_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['bad_reviews_script_it']) ?
                    json_decode($registerPageScript['bad_reviews_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['bad_reviews_script_sp']) ?
                    json_decode($registerPageScript['bad_reviews_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['bad_reviews_script_jp']) ?
                    json_decode($registerPageScript['bad_reviews_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['bad_reviews_script']) ?
                    json_decode($registerPageScript['bad_reviews_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }


    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getCommentLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['comment_page_script_ger']) ?
                    json_decode($registerPageScript['comment_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['comment_page_script_it']) ?
                    json_decode($registerPageScript['comment_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['comment_page_script_sp']) ?
                    json_decode($registerPageScript['comment_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['comment_page_script_jp']) ?
                    json_decode($registerPageScript['comment_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['comment_page_script']) ?
                    json_decode($registerPageScript['comment_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }

    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getAmazonCommentLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['amazon_comment_page_script_ger']) ?
                    json_decode($registerPageScript['amazon_comment_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['amazon_comment_page_script_it']) ?
                    json_decode($registerPageScript['amazon_comment_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['amazon_comment_page_script_sp']) ?
                    json_decode($registerPageScript['amazon_comment_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['amazon_comment_page_script_jp']) ?
                    json_decode($registerPageScript['amazon_comment_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['amazon_comment_page_script']) ?
                    json_decode($registerPageScript['amazon_comment_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }


    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getGiftProductLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['gift_product_page_script_ger']) ?
                    json_decode($registerPageScript['gift_product_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['gift_product_page_script_it']) ?
                    json_decode($registerPageScript['gift_product_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['gift_product_page_script_sp']) ?
                    json_decode($registerPageScript['gift_product_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['gift_product_page_script_jp']) ?
                    json_decode($registerPageScript['gift_product_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['gift_product_page_script']) ?
                    json_decode($registerPageScript['gift_product_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }


    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getGiftEndLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['gift_end_page_script_ger']) ?
                    json_decode($registerPageScript['gift_end_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['gift_end_page_script_it']) ?
                    json_decode($registerPageScript['gift_end_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['gift_end_page_script_sp']) ?
                    json_decode($registerPageScript['gift_end_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['gift_end_page_script_jp']) ?
                    json_decode($registerPageScript['gift_end_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['gift_end_page_script']) ?
                    json_decode($registerPageScript['gift_end_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }

    /**
     * @Notes:前端激活获取多语言
     * @Interface getActivateLanguage
     * @param $registerPageScript
     * @param $language
     * @return mixed
     * @author: wuyu
     * @Time: 2023/7/19   15:54
     */
    public function getGiftSelectLanguage($registerPageScript,$language)
    {
        //获取多语言
        $registerInfo = [];
        switch ($language){
            case 'ger':
                $registerInfo = !empty($registerPageScript['gift_select_page_script_ger']) ?
                    json_decode($registerPageScript['gift_select_page_script_ger'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'it':
                $registerInfo = !empty($registerPageScript['gift_select_page_script_it']) ?
                    json_decode($registerPageScript['gift_select_page_script_it'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'sp':
                $registerInfo = !empty($registerPageScript['gift_select_page_script_sp']) ?
                    json_decode($registerPageScript['gift_select_page_script_sp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'jp':
                $registerInfo = !empty($registerPageScript['gift_select_page_script_jp']) ?
                    json_decode($registerPageScript['gift_select_page_script_jp'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
            case 'en':
            default:
                $registerInfo = !empty($registerPageScript['gift_select_page_script']) ?
                    json_decode($registerPageScript['gift_select_page_script'], true) :
                    json_decode('{"script_1": ""}', true);
                break;
        }
        return $registerInfo;
    }


    /**
     * @Notes:确认礼品 产品提交
     * @Interface confirmProduct
     * @author: wuyu
     * @Time: 2023/4/17   14:44
     */
    public function confirmProduct()
    {

        $param = request()->all();
        $name = $param['name'] ?? '';
        $email = $param['email'] ?? '';
        $orderId = $param['order_id'] ?? '';
        $address = $param['address'] ?? '';
        $city = $param['city'] ?? '';
        $comment = $param['comment'] ?? '';
        $country = $param['country'] ?? '';
        $giftType = $param['gift_type'] ?? '';
        $orderEmail = $param['order_email'] ?? '';
        $orderName = $param['order_name'] ?? '';
        $phone = $param['phone'] ?? '';
        $postalCode = $param['postal_code'] ?? '';
        $rate = $param['rate'] ?? '';
        $state = $param['state'] ?? '';
        $productTitle = $param['product_title'] ?? '';
        $asin = $param['asin'] ?? '';
        $giftName = $param['gift_name'] ?? '';
        $giftType2 = $param['gift_type_2'] ?? '';
        $giftImage = $param['gift_image'] ?? '';
        $sensitiveUser = $param['sensitive_user'] ?? '';
        $platformSku = $param['platform_sku'] ?? '';
        $brandCode = $param['brand_code'] ?? '';
        $displayGiftSelectView = $param['display_gift_select_view'] ?? 0;
        $progressStarRatingEvaluation = $param['progress_star_rating_evaluation'] ?? 0;
        $progressBadReviews = $param['progress_bad_reviews'] ?? 0;
        $progressConfirmGift = $param['progress_confirm_gift'] ?? 0;
        $progressFavorableComment = $param['progress_favorable_comment'] ?? 0;
        $progressFavorableCommentJumpAmazon = $param['progress_favorable_comment_jump_amazon'] ?? 0;
        $progressWriteAddress = $param['progress_write_address'] ?? 0;
        $noVerify = $param['no_verify'] ?? '';


        if (empty($noVerify)){ //买家端设置后 部分流程不会走产品页面
            if (empty($orderName)) {
                return message("OrderName is invaild!", false, []);
            }
            if (empty($orderEmail)) {
                return message("Email is invaild!", false, []);
            }
            if (empty($orderId)) {
                return message("Order is invaild!", false, []);
            }
            if (empty($address)) {
                return message("Address is invaild!", false, []);
            }
            if (empty($city)) {
                return message("City is invaild!", false, []);
            }
            if (empty($country)) {
                return message("Country is invaild!", false, []);
            }
            if (empty($phone)) {
                return message("Phone is invaild!", false, []);
            }
            if (empty($postalCode)) {
                return message("Postal Code is invaild!", false, []);
            }
            if (empty($state)) {
                return message("State/Region is invaild!", false, []);
            }
        }


        //查找记录是否存在
        $info = $this->model->where([['order_id', '=', $orderId]])->where('mark','=',1)->first();
        if (empty($info)) return message("Activation information does not exist", false, []);
//        if (!empty($info['progress_confirm_gift'])) return message("礼品信息已经提交过,请勿重复提交", false, []);

        //获取订单信息
        $OrderAndCustomersOrderModel = new OrderAndCustomersOrderModel();
        $OrderAndCustomersOrderExtendModel = new OrderAndCustomersOrderExtendModel();
        $order = $OrderAndCustomersOrderModel
            ->where(['order_id' => $orderId, 'mark' => 1])
            ->first(['id', 'order_id','buyer_name','buyer_mail','country_name','user_account','amount_paid','platform_paid_date']);
        $orderExt = $OrderAndCustomersOrderExtendModel->where(['order_id' => $order['id']])->first();
        $takeOverAddress = '';
        if (!empty($orderExt['line1'])) $takeOverAddress = $orderExt['line1'] . ' ' . $orderExt['line2'] . ' ' . $orderExt['line3'];

        $mainData = [
            'asin' => $asin,
            'platform_sku' => $platformSku,
            'brand_code' => $brandCode,
            'account' => $order['user_account'] ?? '',
            'order_country' => $country,
            'gift_type' => $giftType,
            'evaluate_star_rating' => $rate,
            'progress_confirm_gift' => $progressConfirmGift,
            'progress_star_rating_evaluation' => $progressStarRatingEvaluation,
            'progress_bad_reviews' => $progressBadReviews,
            'progress_favorable_comment' => $progressFavorableComment,
            'progress_favorable_comment_jump_amazon' => $progressFavorableCommentJumpAmazon,
            'progress_write_address' => $progressWriteAddress,
            'purchase_time' => $order['platform_paid_date'] ?? '',
            'step_end_update_time'=>time(),
            'update_time'=>time()
        ];
        $OrderAndCustomersOrderDetailModel = new OrderAndCustomersOrderDetailModel();
        $detailData = $OrderAndCustomersOrderDetailModel->getOne([
            ['order_id','=',($order['id'] ?? 0) ],
            ['platform_sku','=',$platformSku],
        ],'product_category_name1',false,false);

        $infoData = [
            'activate_user_id'=>$info['id'],
            'order_name' => $orderName,
            'sensitive_user' => $sensitiveUser,
            'gift_name' => $giftName,
            'gift_type_2' => $giftType2,
            'order_address' => $address,
            'gift_image' => str_replace(env('IMG_URL'), "", $giftImage),
            'order_city' => $city,
            'comment' => $comment,
            'order_email' => $orderEmail,
            'order_phone' => $phone,
            'order_postal_code' => $postalCode,
            'order_state' => $state,
            'take_over_name' => $order['buyer_name'] ?? '',
            'take_over_email' => $order['buyer_mail'] ?? '',
            'take_over_address' => $takeOverAddress,
            'take_over_city' => $orderExt['city_name'] ?? '',
            'take_over_state' => $orderExt['state'] ?? '',
            'take_over_postal_code' => $orderExt['postal_code'] ?? '',
            'take_over_country' => $order['country_name'] ?? '',
            'product_title' => $productTitle,
            'all_price' => $order['amount_paid'] ?? 0.00,
            'discount' => $order['discount_val'] ?? 0.00,
            'product_category_name'=>$detailData['product_category_name1'] ?? ''
        ];

        //自动打标签
//        $tagName = '';
//        if (!empty($info['progress_activate']) && $info['progress_activate']!=3){
//            $tagName='普通用户';
//        }
//        if (!empty($mainData['progress_star_rating_evaluation']) && $mainData['evaluate_star_rating'] >=4){
//            $tagName='优质用户';
//        }elseif(!empty($mainData['progress_star_rating_evaluation']) && $mainData['evaluate_star_rating'] >0 && $mainData['evaluate_star_rating'] <4){
//            $tagName='风险用户';
//        }
//        if (!empty($mainData['progress_confirm_gift'])){
//            $tagName='普通用户';
//        }
//        if (!empty($mainData['progress_bad_reviews'])){
//            $tagName='风险用户';
//        }
//        if (!empty($mainData['progress_favorable_comment'])){
//            $tagName='优质用户';
//        }
//        $TagManageModel = new TagManageModel();
//        $ActivateUserManagementTagModel = new ActivateUserManagementTagModel();
//        # 自动打标签
//        if (!empty($tagName)){
//            $tagRow = $TagManageModel->getOne([
//                ['tag_name','=',$tagName]
//            ]);
//            if (!empty($tagRow)){
//                $ActivateUserManagementTagModel->where('activate_user_id', $info['id'])->delete();
//                $tagData = [
//                    'activate_user_id' => $info['id'],
//                    'tag_manage_id' => $tagRow['id']
//                ];
//                $ActivateUserManagementTagModel->insert($tagData);
//            }
//        }


        //获取用户名
        $UserAccountModel = new UserAccountModel();
        $ActivateUserManagementInfoModel = new ActivateUserManagementInfoModel();
        $userAccountData = $UserAccountModel->getOne([
            ['account_name','=',$mainData['account']]
        ]);
        if (!empty($userAccountData)) $mainData['create_user'] = $userAccountData['user_id'];

        $result = $this->model->where("id", $info['id'])->update($mainData);
        if (!$result) return message("Data save failed", false);
        $this->model->cacheReset($info['id'], $mainData, $info['id']);

        //判断是否存在信息
        $infoExists = $ActivateUserManagementInfoModel->where('activate_user_id','=',$info['id'])->first();

        if (!empty($infoExists)){
            $ActivateUserManagementInfoModel->where('activate_user_id','=',$info['id'])->update($infoData);
        }else{
            $ActivateUserManagementInfoModel->where('activate_user_id','=',$info['id'])->insert($infoData);
        }

        return message("Successfully submitted product", true, []);

    }

    public function confirmComment()
    {
        $param = request()->all();
        $name = $param['name'] ?? '';
        $email = $param['email'] ?? '';
        $orderId = $param['order_id'] ?? '';
        $giftType = $param['gift_type'] ?? '';
        $rate = $param['rate'] ?? '';
        $comment = $param['comment'] ?? '';
        if (empty($email)) {
            return message("Email is invaild!", false, []);
        }
        if (empty($orderId)) {
            return message("Order is invaild!", false, []);
        }
        if (empty($giftType)) {
            return message("Gift type is invaild!", false, []);
        }
        if (empty($rate)) {
            return message("Star is invaild!", false, []);
        }
        if (empty($comment)) {
            return message("Comment is invaild!", false, []);
        }

        //查找记录是否存在
        $info = $this->model->where([['order_id', '=', $orderId]])->first();
        if (empty($info)) return message("Activation information does not exist", false, []);
        if (!empty($info['progress_confirm_gift'])) return message("The gift information has been submitted, please do not resubmit it", false, []);

        $data = [
            'gift_type' => $giftType,
            'comment' => $comment,
            'evaluate_star_rating' => $rate,
            'progress_confirm_gift' => 1,
            'create_time' => time()
        ];
        $result = $this->model->where("id", $info['id'])->update($data);

        if (!$result) return message("Data submission failed", false);
        return message("Submitted successfully", true, []);


    }


    /**
     * @Notes:检查邮箱格式
     * @Interface checkEmail
     * @author: wuyu
     * @Time: 2023/7/5   12:15
     */
    public function checkEmail()
    {
        $param = request()->all();
        $email = $param['email'] ?? '';
        $CommonService = new CommonService();
        $emailResponse = $CommonService->emailPreg($email);
//        $emailFormat = $CommonService->emailFormat($email);
        if (!$emailResponse) return message("Email is invaild!", false, []);
        return message("successfully", true, []);
    }

}
